package com.pantuo.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pantuo.common.utils.HttpClientPool;
import com.pantuo.common.utils.HttpClientUtil;
import com.pantuo.sys.dao.LineDao;
import com.pantuo.sys.dao.SfzLogDao;
import com.pantuo.sys.dao.StatisticsOneDao;
import com.pantuo.sys.dao.VehicleDao;
import com.pantuo.sys.service.WeChatWarnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 炳秦
 * @Date: 2021/08/02/14:27
 * @Description:
 */
@Service
public class WeChatWarnServiceImpl implements WeChatWarnService {

    @Autowired
    private LineDao lineDao;
    @Autowired
    private VehicleDao vehicleDao;
    @Autowired
    private SfzLogDao sfzLogDao;
    @Autowired
    private StatisticsOneDao statisticsOneDao;
    

    /***
    * @Description: 每天六点开启定时任务，匹对该月统计数据是否一致
    * @Param: []
    * @return: void
    * @Author: 炳秦
    * @Date: 2021/8/2 15:33
    */
    @Override
    public void checkLineAndVehicle() {
        String startDate = "2021-08-01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String endDate = sdf.format(new Date());
        String month = endDate.substring(5, 7);
        int lineStaCount = lineDao.findCountForLine(startDate, endDate);
        //历史车辆统计数量
        int vehicleStaCount = vehicleDao.findCountForVehicle(startDate, endDate);
        String title = "泰安市公共有限公司乘车识别系统";
        String desp = null;
        if (lineStaCount != vehicleStaCount){
            desp = month+"月历史线路与历史车辆统计数据存在差异";
            try {
                title = URLEncoder.encode(title, "UTF-8");
                desp = URLEncoder.encode(desp, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpClientPool.doGet(
                    "http://sctapi.ftqq.com/SCT57418TN0tJiCa0pkN493peaeJeSKAa.send?title="+title+"&desp="+desp+"",
                    null,
                    "UTF-8",
                    2350,
                    2350,
                    true);
        }
    }


    @Override
    public int checkIDLength() {
        String url = "jdbc:mysql://localhost:3306/oa_data3?serverTimezone=GMT%2B8&characterEncoding=utf8";
        String user = "root";
        String password = "pantuo1709";
        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new Date());
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
            String sql = "select log_s from tn_sfzlog where created_dt like '"+date+"%' and bind_i = 1 and r_s = '1'";
            statement = conn.prepareStatement(sql);
            //关键：做一下设置会采用流数据接收方式，每次从服务器接收部分数据，直到所有数据处理完毕，不会发生JVM OOM
            statement.setFetchSize(Integer.MIN_VALUE);
            resultSet = statement.executeQuery();
            int count = 0;
            while (resultSet.next()){
                String log_s = resultSet.getString("log_s");
                System.out.println(log_s);
                Map map = (Map) JSON.parse(log_s);
                Object words_result = map.get("words_result");
                String str = JSON.toJSONString(words_result);
                JSONArray objects = JSON.parseArray(str);
                Object[] objects1 = objects.stream().toArray();
                int length = objects1.length;
                Map map1 = (Map) objects.get(length - 1);
                String words = (String) map1.get("words");
                String regEx= "[^0-9]" ;
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(words);
                String ID = m.replaceAll("").trim();
                if (ID.length() <= 10){
                    count ++;
                }
            }
            String title = URLEncoder.encode("泰安市公共有限公司乘车识别系统", "UTF-8");
            String desp = URLEncoder.encode("今天有"+count+"次识别的身份证长度不正常，请注意查看", "UTF-8");
            return count;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return 0;

    }

    //晚上9点发送
    @Scheduled(cron = "0 0 21 * * * ")
    @Override
    public void calculationThisMonthNum() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String date_s = sdf.format(new Date());
        Calendar instance = Calendar.getInstance();
        int month = instance.get(Calendar.MONTH) + 1;
        //车辆历史总数
        int vehicleCount = vehicleDao.findThisMonthCount(date_s);
        //线路历史总数
        int lineCount = lineDao.findThisMonthCount(date_s);
        //刷卡明细历史总数
        int sfzLogCount = sfzLogDao.findThisMonthCount(date_s);
        //每天历史统计总数
        int currentDayCount = statisticsOneDao.findThisMonthCount(date_s);
        //识别异常条数
        int exceptionCount = checkIDLength();
        String lengthExceptionMsg;
        if (exceptionCount == 0){
            lengthExceptionMsg = "今日识别长度无异常！";
        }else {
            lengthExceptionMsg = "今日识别有"+exceptionCount+"条长度异常，请及时处理！";
        }
        String result = HttpClientPool.doGet(
                "https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                "corpid=ww44f4eb1850de9bf1&corpsecret=g8SntezOliUgPrM_SgBph4VEQmzQL9D1QOKXUR6W3r0",
                "UTF-8",
                25000,
                25000,
                true
        );
        System.out.println(lengthExceptionMsg);
        String access_token = JSONObject.parseObject(result).get("access_token").toString();
        Map<String, Object> paramMap = new HashMap<String, Object>()
        {
            Map<String, String> contentMap = new HashMap<>();
            {
                put("touser", "@all");
                put("msgtype", "text");
                put("agentid", 1000002);
                //jsonStr.getBytes(“UTF-8”);
                contentMap.put("content", "泰安公共有限公司乘车识别系统\n" +
                        ""+month+"月每天历史统计表总数："+currentDayCount+"" +
                        "\n"+month+"月车辆历史统计表总数："+vehicleCount+"" +
                        "\n"+month+"月线路历史统计表总数："+lineCount+"" +
                        "\n"+month+"月刷卡明细日志表总数："+sfzLogCount+"" +
                        "\n"+lengthExceptionMsg);
                put("text", contentMap);
            }
        };
        JSONObject jsonObject = new JSONObject(paramMap);
        Map<String, String> headMap = new HashMap<>();
        headMap.put("access_token", access_token);
        HttpClientUtil.sendPostByJsonObj(jsonObject, "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token+"");
    }

    public String getAccessToken(){
        String result = HttpClientPool.doGet(
                "https://qyapi.weixin.qq.com/cgi-bin/gettoken",
                "corpid=ww44f4eb1850de9bf1&corpsecret=g8SntezOliUgPrM_SgBph4VEQmzQL9D1QOKXUR6W3r0",
                "UTF-8",
                25000,
                25000,
                true
        );
        String access_token = JSONObject.parseObject(result).get("access_token").toString();
        return access_token;
    }

    /*@Scheduled(cron = "0 0 18 * * * ")
    public void execute(){
        checkLineAndVehicle();
        checkIDLength();
    }*/


}
